package com.itheima.controller;

import com.itheima.domain.Student;
import com.itheima.factory.Factory;
import com.itheima.service.IStudentService;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;



public class ImplStudentController implements IStudentController {

    private IStudentService studentService = Factory.getStudentService();
    Scanner sc = new Scanner(System.in);
    private String id;


    @Override
    public void addStudent() throws IOException {
        while (true) {
            System.out.println("请输入学号");
            id = sc.next();
            boolean exist = studentService.isExist(id);
            if (exist) {
                System.out.println("学号已存在，请重新输入：");
            } else {
                break;
            }
        }
        Student student = getStudentInfo(id);
        studentService.addStudent(student);
        System.out.println("添加成功！");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ItHeiMaSystem\\myStreamFile/student.txt"));
        oos.writeObject(student);
        oos.close();
    }

    public Student getStudentInfo(String id) {
        System.out.println("请输入姓名：");
        String name = sc.next();
        System.out.println("请输入性别：");
        String gender = sc.next();
        System.out.println("请输入班级：");
        String classes = sc.next();
        System.out.println("请输入组号：");
        int group = sc.nextInt();
        System.out.println("请输入手机号");
        String phone = sc.next();
        System.out.println("请输入生日：");
        LocalDate birthdayDate;
        while (true) {
            String birthday = sc.next();
            try {
                birthdayDate = LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                break;
            } catch (DateTimeParseException e) {
                System.out.println("日期格式输入有误，请重新输入：（标准格式：yyyy-MM-dd）");
            }
        }
        int age=Period.between(birthdayDate,LocalDate.now()).getYears();
        Student student = new Student(id, name, gender, classes, group, phone,birthdayDate,age);
        return student;
    }

    @Override
    public void deleteStudent() {
        ArrayList<Student> allStudent = studentService.findAllStudent();
        if (allStudent.isEmpty()) {
            System.out.println("没有数据，请先添加！");
            return;
        }
        studentService.deleteStudent(id);
        System.out.println("删除成功!");

    }

    public String getStudentId() {
        while (true) {
            System.out.println("请输入学号：");
            id = sc.next();
            boolean exist = studentService.isExist(id);
            if (exist) {
                break;
            } else {
                System.out.println("学号不存在，请重新输入：");
            }
        }
        return id;
    }

    @Override
    public void updateStudent() {
        ArrayList<Student> allStudent = studentService.findAllStudent();
        if (allStudent.isEmpty()) {
            System.out.println("没有数据，请先添加！");
            return;
        }
        String id = getStudentId();
        Student newstu = getStudentInfo(id);
        studentService.updateStudent(id, newstu);
        System.out.println("修改成功!");
    }


    @Override
    public void findAllStudent() {
        ArrayList<Student> allStudent = studentService.findAllStudent();
        System.out.println("学号\t\t姓名\t\t性别\t\t班级\t\t组号\t\t手机号\t\t生日\t\t年龄");
        for (int i = 0; i < allStudent.size(); i++) {
            Student student = allStudent.get(i);
            System.out.println(student.getId() + "\t" + student.getName() + "\t\t" + student.getGender()
                    + "\t\t" + student.getClasses() + "\t\t" + student.getGroup() + "\t\t" + student.getPhone()
                    + "\t\t" + student.getBirthday() + "\t\t" + student.getAge());
        }
    }

    @Override
    public void show() {
        System.out.println("请输入您的选择:1.姓名找学生 2.手机号找学生 3.查看学生的分布 4.返回");
        String choice = sc.next();
            switch (choice) {
                case "1":
                    findStuByName();
                    break;
                case "2":
                    findStuByphone();
                    break;
                case "3":
                    stuTongJi();
                    break;
                case "4":
                    System.out.println("返回上一级");
                    return;
                default:
                    System.out.println("输入有误,请重新输入");
                    break;
            }
        }

    private void stuTongJi() {
        ArrayList<Student> allStudent = studentService.findAllStudent();
        System.out.println("当前系统总人数为："+allStudent.size()+"人");
        long manNum = allStudent.stream().filter(student -> student.getGender().equals("男")).count();
        System.out.println("男生有"+manNum+"人");
        long womanNum = allStudent.stream().filter(student -> student.getGender().equals("女")).count();
        System.out.println("女生有"+womanNum+"人");
        long shiBaSui = allStudent.stream().filter(student -> student.getAge() == 18).count();
        System.out.println("18岁的有"+shiBaSui+"人");
        long shiJiuSui = allStudent.stream().filter(student -> student.getAge() == 19).count();
        System.out.println("19岁的有"+shiJiuSui+"人");
        long erShiSui = allStudent.stream().filter(student -> student.getAge() == 20).count();
        System.out.println("20岁的有"+erShiSui+"人");
        long banjiNum = allStudent.stream().filter(student -> student.getClasses().equals("32期")).count();
        System.out.println("32期有"+banjiNum+"人");
        HashMap<Integer,ArrayList<Student>> map = new HashMap<>();
        for (Student student : allStudent) {
            int group = student.getGroup();
            if (map.containsKey(group)){
                map.get(group).add(student);
            }else {
                ArrayList<Student> groupList = new ArrayList<>();
                groupList.add(student);
                map.put(group,groupList);
            }
        }
        HashMap<Integer,Integer> avgAge = new HashMap<>();
        Set<Integer> keySet = map.keySet();
        for (Integer it : keySet) {
            ArrayList<Student> stus = map.get(it);
            int sum = 0;
            for (int i = 0; i < stus.size(); i++) {
                Student szy = stus.get(i);
                int age = szy.getAge();
                sum += age;
            }
            int avg = sum / stus.size();
            avgAge.put(it,avg);
        }
        avgAge.forEach((k,v)->System.out.println(k+"组的平均年龄为: "+ v));
        map.forEach((k,v)-> System.out.println(k + "组的人数为: " + v.size()));
    }

    private void findStuByName(){
        System.out.println("请输入要查找的学生姓名：");
        String name = sc.next();
        ArrayList<Student> stuList = studentService.findStuByName(name);
        if (stuList.isEmpty()){
            System.out.println("查无此人！");
        }else{
            for (Student student : stuList) {
                System.out.println(student);
            }
        }
    }
    private void findStuByphone(){
        System.out.println("请输入要查找学生的手机号码：");
        String phone=sc.next();
        Student student = studentService.findStuByphone(phone);
        if (student ==null){
            System.out.println("查无此人！");
        }else{
            System.out.println(student);

        }
    }

}
